package demo.spring.framework.transaction.support;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import demo.db.dynamic.config.DynamicDsDemoConfig;
import demo.db.mybatis.pojo.User;
import demo.db.mybatis.service.UserService;
import demo.spring.framework.jdbc.datasource.lookup.RoutingDataSourceDemo;

public class TransactionSynchronizationManagerDemo {

    /**
     * TransactionSynchronizationManager基本上充当TransactionSynchronization的注册表.
     * javadoc说
     * <p>
     * If transaction synchronization isn’t active,there is either no current
     * transaction,or the transaction manager doesn’t support transaction
     * synchronization.
     * <p>
     * 因此,您首先使用initSynchronization()和registerSynchronization(TransactionSynchronization)初始化并注册TransactionSynchronization.
     * 注册这些时,TransactionManager可以启动一个Transaction,并通过setActualTransactionActive(boolean)告诉TransactionSynchronizationManager它是否处于活动状态.
     * 
     * 总之,isSynchronizationActive()告诉我们是否已启用TransactionSynchronization,即使没有注册任何TransactionSynchronization实例.
     * 
     * isActualTransactionActive()告诉我们实际的Transaction对象是否处于活动状态.
     * 
     * TransactionSynchronizationManager javadoc说明
     * 
     * Central helper that manages resources and transaction synchronizations per
     * thread. To be used by resource management code but not by typical application
     * code.
     * 
     * 所以不要忽视它.
     * 
     * 
     */
    @Test
    public void test() {
        TransactionSynchronizationManager.initSynchronization();

        TransactionSynchronization synchronization = null;
        TransactionSynchronizationManager.registerSynchronization(synchronization);

        TransactionSynchronizationManager.isActualTransactionActive();

        TransactionSynchronizationManager.isSynchronizationActive();
    }

    /**
     * 使用TransactionSynchronizationManager在事务提交之后操作
     */
    @Test
    public void testAfterCommit() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(DynamicDsDemoConfig.class);
        context.refresh();
        UserService userService = context.getBean(UserService.class);
        userService.insertAndFlagIfCommit("Stan");
        System.err.println("--------------");
        context.close();
    }

}
